package com.atzly.community.datasource;

/**
 * 获取当前线程上下文的数据源
 * 不能从上下文环境取数据源，因为当前线程可能会涉及到多个数据源
 */
public class DataSourceContextHolder {
  private static final ThreadLocal<String> dataSource = new ThreadLocal<String>();

  public static void setDataSourceWithDbId(String dbId) {
    setDataSource(DataSourceConstants.DYNAMIC_DATA_SOURCE_NAME + DataSourceConstants.SEPARATOR_CHAR + dbId);
  }

  public static void setDefaultDataSource() {
    setDataSource(DataSourceConstants.DEFAULT_DATA_SOURCE_NAME);
  }

  public static void setSlaveDataSource(String dbId) {
    setDataSource(DataSourceConstants.SLAVE_DYNAMIC_DATA_SOURCE_NAME + DataSourceConstants.SEPARATOR_CHAR + dbId );
  }

  private static void setDataSource(String dataSourceName) {
    dataSource.set(dataSourceName);
  }

  public static String getDataSource() {
    return (String) dataSource.get();
  }

  public static void clearDataSource() {
    dataSource.remove();
  }

}
